﻿using Autofac.Core;
using Biotech.Log;
using OxyPlot;
using project.B12.application.Extensions;
using project.B12.application.Ioc;
using project.B12.application.Views.Dialogs;
using project.B12.IRepository;
using project.B12.IService;
using project.B12.Model.BaseModel;
using project.B12.Model.Common;
using project.B12.Model.Enums;
using project.B12.Model.Models;
using project.B12.Model.Res;
using project.B12.Service;
using project.B12.ViewModels;
using project.B12.Views.Dialog;
using software.Common.MVVM;
using software.dll.user;
using Software.Common.Util.AppConfig;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Xml;
using System.Xml.Linq;
using WPFDevelopers.Controls;

namespace project.B12.application.ViewModels.Setting
{
    public class UserSettingViewModel : ObservableObject
    {
        public IUserService UserService { get; set; }

        private IServiceDevice serviceDevice { get; set; }

        private IMICPlateMes mICPlateMes { get; set; }

        private IMonitorMesRepository monitorMesRepository { get; set; }

        private PublicResourceViewModel publicResourceViewModel { get; set; }

        public UserSettingViewModel(IUserService userService,
            IServiceDevice _serviceDevice,
            IMICPlateMes _mICPlateMes,
            IMonitorMesRepository _monitorMesRepository)
        {
            UserService = userService;
            serviceDevice = _serviceDevice;
            mICPlateMes= _mICPlateMes;
            monitorMesRepository= _monitorMesRepository;
            publicResourceViewModel = ViewModelLocator.PublicResourceViewModel;
            //Initialization();
        }

        /// <summary>
        /// 初始化
        /// </summary>
        public void Init()
        {
            ChangePassword.ClearPassword();
            ChangePassword.ClearTips();
            NewUser.ClearTips();
            NewUser.ClearInfo();
            AddDepartment = string.Empty;
            RoleRightModelList = new ObservableCollection<RoleRightModel>();
            if (UtilAppConfig.ExistItem("Login_LockedTime"))
                LockedTimeConfig = Convert.ToInt32(UtilAppConfig.GetItem("Login_LockedTime"));
        }

        #region 用户清单
        #region Command命令
        public RelayCommand UserSetQueryCommand => new RelayCommand(UserSetQuery);//用户清单查询
        public RelayCommand UserSetResetCommand => new RelayCommand(UserSetReset);//用户清单重置
        public RelayCommand<UserModel> UserSetEnableCommand => new RelayCommand<UserModel>(UserSetEnable);//用户清单设置可用性
        public RelayCommand<string> ResetPasswordCommand => new RelayCommand<string>(ResetPassword);//用户清单设置重置密码
        public RelayCommand<UserModel> ExpirationTimeCommand => new RelayCommand<UserModel>(ExpirationTime);//用户清单设置过期时间
        public RelayCommand<string> UserSetDelCommand => new RelayCommand<string>(UserSetDel);//用户设置删除
        #endregion
        #region Method方法
        /// <summary>
        /// 查询用户
        /// </summary>
        private void UserSetQuery()
        {
            try
            {
                var result = UserService.GetAllUsers();//查询用户
                if (result.Item1.Success)
                    WPF.Controls.Message.Push(String.Format(Resources.QuerySuccessful, result.Item2.Count()), MessageBoxImage.Information);
                else
                    WPF.Controls.Message.Push(Resources.QueryFailed + $":+{result.Item1.Message}", MessageBoxImage.Error);
            }
            catch (Exception ex)
            {
                WPF.Controls.Message.Push(Resources.UnknownError + $":{ex}", MessageBoxImage.Error);
            }
        }

        /// <summary>
        /// 重置用户清单
        /// </summary>
        private void UserSetReset()
        {
            try
            {
                var result = UserService.ResetUsersList();//重置用户清单
                if (result.Success)
                    WPF.Controls.Message.Push(Resources.ResetSuccessful, MessageBoxImage.Information);
                else
                    WPF.Controls.Message.Push(Resources.ResetFailed + $":{result.Message}", MessageBoxImage.Error);
            }
            catch (Exception ex)
            {
                WPF.Controls.Message.Push(Resources.UnknownError + $":{ex}", MessageBoxImage.Error);
            }
        }

        /// <summary>
        /// 更改账户可用性
        /// </summary>
        /// <param name="name"></param>
        private void UserSetEnable(UserModel userModel)
        {
            try
            {
                var result = UserService.ChangeLockedState(userModel);//更改账户可用性
                if (result.Success)
                    WPF.Controls.Message.Push(String.Format(Resources.AccountUsabilityChangedSuccessfully, userModel.Name), MessageBoxImage.Information);
                else
                    WPF.Controls.Message.Push(String.Format(Resources.AccountUsabilityChangedFailed, userModel.Name) + $":{result.Message}", MessageBoxImage.Error);
            }
            catch (Exception ex)
            {
                WPF.Controls.Message.Push(Resources.UnknownError + $":{ex}", MessageBoxImage.Error);
            }
        }

        /// <summary>
        /// 用户密码重置
        /// </summary>
        /// <param name="name">用户名</param>
        private async void ResetPassword(string name)
        {
            try
            {
                if (UserService.GetUserRight(RightEnum.UserManagerResetPassword))
                {
                    if (name != string.Empty)
                    {
                        var Result = await ResetPasswordView.ResetPassword(name, "Main");
                        if (!string.IsNullOrEmpty(Result))
                        {
                            var result = UserService.UpdateUser(name, Result);
                            if (result.Success)
                            {
                                LoggerFactory.Instance.CurrentLogger.LogInfo($"用户“{name}”密码已完成重置！\n①用户名：({UserService.CurrentUser.Name})\n②角色名：({UserService.CurrentUser.RoleName})", "", "软件");
                                WPF.Controls.Message.Push(String.Format(Resources.UserPasswordResetSuccessful, name), MessageBoxImage.Information);
                            }
                            else
                            {
                                WPF.Controls.Message.Push(String.Format(Resources.UserPasswordResetFailed, name) + $":{result.Message}", MessageBoxImage.Error);
                            }
                        }
                        else
                            WPF.Controls.Message.Push(Resources.OperationCanceled, MessageBoxImage.Question);
                    }
                }
                else
                    WPF.Controls.Message.Push(Resources.InsufficientPermission, MessageBoxImage.Error);
            }
            catch (Exception ex)
            {
                WPF.Controls.Message.Push(Resources.UnknownError + $":{ex}", MessageBoxImage.Error);
            }
        }

        /// <summary>
        /// 过期时间设置
        /// </summary>
        /// <param name="name"></param>
        private async void ExpirationTime(UserModel userModel)
        {
            try
            {
                if (UserService.GetUserRight(RightEnum.UserManagerExpirationTime))
                {
                    if (userModel != null)
                    {
                        var Result = await ExpirationTimeView.ExpirationTime(userModel, "Main");
                        if (Result != null)
                        {
                            var result = UserService.UpdateExpirationTime(userModel.Name, Result);
                            if (result.Success)
                            {
                                LoggerFactory.Instance.CurrentLogger.LogInfo($"用户“{userModel.Name}”过期策略已更新！\n①用户名：({UserService.CurrentUser.Name})\n②角色名：({UserService.CurrentUser.RoleName})", "", "软件");
                                WPF.Controls.Message.Push(String.Format(Resources.ExpirationTimeUpdatedSuccessful, userModel.Name), MessageBoxImage.Information);
                            }
                            else
                            {
                                WPF.Controls.Message.Push(String.Format(Resources.ExpirationTimeUpdatedFailed, userModel.Name) + $":{result.Message}", MessageBoxImage.Error);
                            }
                        }
                        else
                            WPF.Controls.Message.Push(Resources.OperationCanceled, MessageBoxImage.Question);
                    }
                }
                else
                    WPF.Controls.Message.Push(Resources.InsufficientPermission, MessageBoxImage.Error);
            }
            catch (Exception ex)
            {
                WPF.Controls.Message.Push(Resources.UnknownError + $":{ex}", MessageBoxImage.Error);
            }
        }

        /// <summary>
        /// 删除用户
        /// </summary>
        /// <param name="name"></param>
        private async void UserSetDel(string name)
        {
            try
            {
                if (UserService.GetUserRight(RightEnum.UserManagerDelete))
                {
                    if (name != null)
                    {
                        if (await MessageDialogView.ComfirmMessage(Resources.Tip, Resources.ConfirmDeleteUser))
                        {
                            var result = UserService.DeleteUser(name);
                            if (result.Success)
                            {
                                LoggerFactory.Instance.CurrentLogger.LogInfo($"用户“{name}”已成功删除！\n①用户名：({UserService.CurrentUser.Name})\n②角色名：({UserService.CurrentUser.RoleName})", "", "软件");
                                WPF.Controls.Message.Push(String.Format(Resources.DeleteUserSuccessful, name), MessageBoxImage.Information);
                            }
                            else
                                WPF.Controls.Message.Push(String.Format(Resources.DeleteUserFailed, name) + $":{result.Message}", MessageBoxImage.Error);
                        }
                    }
                }
                else
                    WPF.Controls.Message.Push(Resources.InsufficientPermission, MessageBoxImage.Error);
            }
            catch (Exception ex)
            {
                WPF.Controls.Message.Push(Resources.UnknownError + $":{ex}", MessageBoxImage.Error);
            }
        }
        #endregion
        #endregion

        #region 更改密码
        #region Command命令
        public RelayCommand UserSetClearCommand => new RelayCommand(UserSetClear);//修改密码清空
        public RelayCommand UserSetSaveCommand => new RelayCommand(UserSetSave);//修改密码保存
        #endregion
        #region Model属性
        public ChangePassword ChangePassword { get; set; } = new ChangePassword();
        #endregion
        #region Method方法
        /// <summary>
        /// 修改密码清空
        /// </summary>
        private void UserSetClear()
        {
            try
            {
                ChangePassword.ClearPassword();
                ChangePassword.ClearTips();
            }
            catch (Exception ex)
            {
                WPF.Controls.Message.Push(Resources.UnknownError + $":{ex}", MessageBoxImage.Error);
            }
        }

        /// <summary>
        /// 修改密码
        /// </summary>
        private void UserSetSave()
        {
            try
            {
                ChangePassword.ClearTips();//清空提示信息
                if (string.IsNullOrEmpty(ChangePassword.OldPassword))//旧密码是否为空？
                {//空
                    ChangePassword.OldPasswordTips = Resources.PasswordEmpty;
                    return;
                }
                else
                {//非空
                    var result = UserService.Login(UserService.UserName, ChangePassword.OldPassword, false);//验证原始密码是否正确？
                    if (result.Success)
                    {//正确
                        if (string.IsNullOrEmpty(ChangePassword.NewPassword))//判断新密码是否为空？
                        {//空
                            ChangePassword.NewPasswordTips = Resources.PasswordEmpty;
                            return;
                        }
                        else
                        {//非空
                            var result1 = UserService.CheckPassword(ChangePassword.NewPassword);//验证新密码是否合规
                            if (!result1.Success)
                            {
                                ChangePassword.NewPasswordTips = Resources.PasswordFormat;
                                return;
                            }
                            if (string.IsNullOrEmpty(ChangePassword.ConfirmPassword))//判断确认密码是否为空？
                            {
                                //空
                                ChangePassword.ConfirmPasswordTips = Resources.PasswordEmpty;
                                return;
                            }
                            else
                            {
                                if (ChangePassword.NewPassword != ChangePassword.ConfirmPassword)
                                {
                                    //空
                                    ChangePassword.ConfirmPasswordTips = Resources.PasswordDifferent;
                                    return;
                                }
                                else
                                {
                                    var result2 = UserService.ChangePassword(UserService.UserName, ChangePassword.NewPassword);//提交密码更新
                                    if (result2.Success)//是否修改成功？
                                    {//成功
                                        UserSetClear();//清空信息
                                        WPF.Controls.Message.Push(Resources.PasswordChangeSuccessful, MessageBoxImage.Information);
                                    }
                                    else
                                    {//失败
                                        UserSetClear();//清空信息
                                        WPF.Controls.Message.Push(Resources.PasswordChangeFailed + $":{result2.Message}", MessageBoxImage.Error);
                                    }
                                }
                            }
                        }
                    }
                    else
                    {//有误
                        ChangePassword.OldPasswordTips = Resources.PasswordError;
                    }
                }
            }
            catch (Exception ex)
            {
                WPF.Controls.Message.Push(Resources.UnknownError + $":{ex}", MessageBoxImage.Error);
            }
        }
        #endregion
        #endregion

        #region 新增用户
        #region Command命令
        public RelayCommand UserSetNewUserSaveCommand => new RelayCommand(UserSetNewUserSave);//用户设置新建用户保存按钮
        public RelayCommand UserSetNewUserClearCommand => new RelayCommand(UserSetNewUserClear);//用户设置新建用户清空按钮
        #endregion
        #region Model属性
        public NewUser NewUser { get; set; } = new NewUser();//新建账户
        #endregion
        #region Method方法
        /// <summary>
        /// 用户设置新建用户清空按钮
        /// </summary>
        private void UserSetNewUserClear()
        {
            try
            {
                NewUser.ClearInfo();
                NewUser.ClearTips();
            }
            catch (Exception ex)
            {
                WPF.Controls.Message.Push(Resources.UnknownError + $":{ex}", MessageBoxImage.Error);
            }
        }

        /// <summary>
        /// 用户设置新建用户保存
        /// </summary>
        private void UserSetNewUserSave()
        {
            try
            {
                if (UserService.GetUserRight(RightEnum.UserManagerAdd))
                {
                    NewUser.ClearTips();
                    if (string.IsNullOrEmpty(NewUser.Name))
                    {
                        WPF.Controls.Message.Push(Resources.UsernameEmpty, MessageBoxImage.Warning);
                        return;
                    }
                    if (string.IsNullOrEmpty(NewUser.Password))
                    {
                        NewUser.PasswordTips = Resources.PasswordEmpty;
                        return;
                    }
                    var result = UserService.CheckPassword(NewUser.Password);//验证新密码是否合规
                    if (!result.Success)
                    {
                        NewUser.PasswordTips = Resources.PasswordFormat;
                        return;
                    }
                    if (string.IsNullOrEmpty(NewUser.ConfirmPassword))
                    {
                        NewUser.ConfirmPasswordTips = Resources.PasswordEmpty;
                        return;
                    }
                    if (NewUser.Password != NewUser.ConfirmPassword)
                    {
                        NewUser.ConfirmPasswordTips = Resources.PasswordDifferent;
                        return;
                    }
                    if (NewUser.RoleName == null)
                    {
                        WPF.Controls.Message.Push(Resources.RoleNameEmpty, MessageBoxImage.Warning);
                        return;
                    }
                    if (string.IsNullOrEmpty(NewUser.Department))
                    {
                        WPF.Controls.Message.Push(Resources.DepartmentEmpty, MessageBoxImage.Warning);
                        return;
                    }
                    if (UserService.CurrentUser.RoleName == "管理员" && UserService.CurrentUser.Department != NewUser.Department)
                    {
                        WPF.Controls.Message.Push(Resources.CreateUserDepartmentRestrictions, MessageBoxImage.Warning);
                        return;
                    }
                    if (NewUser.ExpirationTime == null)
                    {
                        WPF.Controls.Message.Push(Resources.ExpirationTimeEmpty, MessageBoxImage.Warning);
                        return;
                    }
                    var result1 = UserService.AddUser(NewUser.Name, NewUser.Password, NewUser.RoleName, NewUser.ExpirationTime, NewUser.Department);
                    if (result1.Success)//是否新增成功？
                    {//成功
                        LoggerFactory.Instance.CurrentLogger.LogInfo($"新用户“{NewUser.Name}”保存成功！\n①用户名：({UserService.CurrentUser.Name})\n②角色名：({UserService.CurrentUser.RoleName})", "", "软件");
                        WPF.Controls.Message.Push(String.Format(Resources.NewUserAddedSuccessfully, NewUser.Name), MessageBoxImage.Information);
                        UserSetNewUserClear();//清空提示信息
                    }
                    else
                    {//失败
                        UserSetNewUserClear();//清空提示信息
                        WPF.Controls.Message.Push(Resources.CreationFailed + $":{result1.Message}", MessageBoxImage.Error);
                    }
                }
                else
                    WPF.Controls.Message.Push(Resources.InsufficientPermission, MessageBoxImage.Error);
            }
            catch (Exception ex)
            {
                WPF.Controls.Message.Push(Resources.UnknownError + $":{ex}", MessageBoxImage.Error);
            }
        }
        #endregion
        #endregion

        #region 部门管理
        #region Command命令
        public RelayCommand UserSetAddDepartmentSaveCommand => new RelayCommand(UserSetAddDepartmentSave);//用户设置新建部门保存按钮
        #endregion
        #region Model属性
        private string addDepartment;//新增部门名称
        public string AddDepartment
        {
            get { return addDepartment; }
            set { addDepartment = value; this.RaisePropertyChanged(); }
        }
        #endregion
        #region Method方法
        /// <summary>
        /// 用户设置新建部门保存
        /// </summary>
        /// <param name="obj"></param>
        private void UserSetAddDepartmentSave()
        {
            try
            {
                if (string.IsNullOrEmpty(AddDepartment))
                {
                    WPF.Controls.Message.Push(Resources.DepartmentEmpty, MessageBoxImage.Warning);
                    return;
                }
                if (string.IsNullOrEmpty(AddDepartment.Trim()))
                {
                    WPF.Controls.Message.Push(Resources.DepartmentEmpty, MessageBoxImage.Warning);
                    return;
                }
                //执行保存方法
                var result = UserService.AddDepartment(AddDepartment);
                if (result.Success)
                {
                    LoggerFactory.Instance.CurrentLogger.LogInfo($"新部门“{AddDepartment}”添加成功！\n①用户名：({UserService.CurrentUser.Name})\n②角色名：({UserService.CurrentUser.RoleName})", "", "软件");
                    AddDepartment = string.Empty;
                    WPF.Controls.Message.Push(Resources.SaveSuccessful, MessageBoxImage.Information);
                }
                else
                    WPF.Controls.Message.Push(Resources.SaveFailed + $":{result.Message}", MessageBoxImage.Error);
            }
            catch (Exception ex)
            {
                WPF.Controls.Message.Push(Resources.UnknownError + $":{ex}", MessageBoxImage.Error);
            }
        }
        #endregion
        #endregion

        #region 权限管理
        #region Command命令
        public RelayCommand UserSetRightListSaveCommand => new RelayCommand(UserSetRightListSave);//用户设置权限清单保存
        #endregion
        #region Model属性
        private RoleEnum roleNameItemsSelectedValue;//当前权限管理选中的角色名
        public RoleEnum RoleNameItemsSelectedValue
        {
            get { return roleNameItemsSelectedValue; }
            set
            {
                roleNameItemsSelectedValue = value;
                try
                {
                    RoleRightModelList = new ObservableCollection<RoleRightModel>(UserService.GetRoleRights(value));
                    WPF.Controls.Message.Push(String.Format(Resources.RightsListOpened, EnumUtil.GetEnumDisplay(value)), MessageBoxImage.Information);
                }
                catch (Exception ex)
                {
                    WPF.Controls.Message.Push(Resources.UnknownError + $":{ex}", MessageBoxImage.Error);
                }
                this.RaisePropertyChanged();
            }
        }
        private ObservableCollection<RoleRightModel> roleRightModelList = new ObservableCollection<RoleRightModel>();//权限清单
        public ObservableCollection<RoleRightModel> RoleRightModelList
        {
            get { return roleRightModelList; }
            set { roleRightModelList = value; RaisePropertyChanged(); }
        }
        #endregion
        #region Method方法
        /// <summary>
        /// 用户设置权限清单保存
        /// </summary>
        private void UserSetRightListSave()
        {
            try
            {
                if (UserService.IsAdmin())
                {
                    if (RoleRightModelList != null && RoleRightModelList.Count != 0)
                    {
                        MessageModel result = UserService.UpdateRoleRight(RoleNameItemsSelectedValue, RoleRightModelList.ToList());
                        if (result.Success)
                        {
                            LoggerFactory.Instance.CurrentLogger.LogInfo($"角色“{RoleNameItemsSelectedValue}”权限保存成功！\n①用户名：({UserService.CurrentUser.Name})\n②角色名：({UserService.CurrentUser.RoleName})", "", "软件");
                            WPF.Controls.Message.Push(Resources.SaveSuccessful, MessageBoxImage.Information);
                        }
                        else
                            WPF.Controls.Message.Push(Resources.SaveFailed + $":{result.Message}", MessageBoxImage.Error);
                    }
                }
                else
                    WPF.Controls.Message.Push(Resources.InsufficientPermission, MessageBoxImage.Error);
            }
            catch (Exception ex)
            {
                WPF.Controls.Message.Push(Resources.UnknownError + $":{ex}", MessageBoxImage.Error);
            }
        }
        #endregion
        #endregion

        #region 其他设置
        #region Command命令
        public RelayCommand UserSetOtherSaveCommand => new RelayCommand(UserSetOtherSave);//用户设置其他设置保存

        public RelayCommand Start => new RelayCommand(StartTest);

        public RelayCommand Discontinue => new RelayCommand(DiscontinueTest);
        #endregion
        #region Model属性
        private int lockedTimeConfig;
        public int LockedTimeConfig
        {
            get { return lockedTimeConfig; }
            set { lockedTimeConfig = value; this.RaisePropertyChanged(); }
        }

        private int shelfCount = 1;
        public int ShelfCount
        {
            get { return shelfCount; }
            set
            {
                shelfCount = value;
                this.RaisePropertyChanged();
            }
        }

        private int indexStart = 1;
        public int IndexStart
        {
            get { return indexStart; }
            set
            {
                indexStart = value;
                this.RaisePropertyChanged();
            }
        }

        private int indexEnd = 5;
        public int IndexEnd
        {
            get { return indexEnd; }
            set
            {
                indexEnd = value;
                this.RaisePropertyChanged();
            }
        }

        private bool startEnabled = true;
        public bool StartEnabled
        {
            get { return startEnabled; }
            set
            {
                startEnabled = value;
                this.RaisePropertyChanged();
            }
        }

        private bool discontinueEnabled = false;
        public bool DiscontinueEnabled
        {
            get { return discontinueEnabled; }
            set
            {
                discontinueEnabled = value;
                this.RaisePropertyChanged();
            }
        }
        
        private readonly Random _random = new Random();
        private int _sampleIdCount = 1;
        #endregion
        #region Method方法
        /// <summary>
        /// 用户设置保存其他设置
        /// </summary>
        /// <param name="obj"></param>
        private void UserSetOtherSave()
        {
            try
            {
                if (UserService.IsAdmin())
                {
                    if (LockedTimeConfig == -1)
                    {
                        WPF.Controls.Message.Push(Resources.SaveFailed, MessageBoxImage.Error);
                        return;//失败
                    }
                    var result = UserService.UpdateLockedTime(LockedTimeConfig);
                    if (result.Success)
                    {
                        LoggerFactory.Instance.CurrentLogger.LogInfo($"密码尝试次数更改成功！\n①用户名：({UserService.CurrentUser.Name})\n②角色名：({UserService.CurrentUser.RoleName})", "", "软件");
                        WPF.Controls.Message.Push(Resources.SaveSuccessful, MessageBoxImage.Information);
                    }
                    else
                        WPF.Controls.Message.Push(Resources.SaveFailed + $":{result.Message}", MessageBoxImage.Error);
                }
                else
                    WPF.Controls.Message.Push(Resources.InsufficientPermission, MessageBoxImage.Error);
            }
            catch (Exception ex)
            {
                WPF.Controls.Message.Push(Resources.UnknownError + $":{ex}", MessageBoxImage.Error);
            }
        }

        private void StartTest()
        {
            if (IndexStart > indexEnd || IndexStart < 0 || IndexStart > 16 || IndexEnd < 0 || IndexEnd > 16)
            {
                WPF.Controls.Message.Push("输入的测试板有误", MessageBoxImage.Warning);
                return;
            }
            if (serviceDevice.deviceState == DeviceState.初始化)
            {
                WPF.Controls.Message.Push("当前正在初始化设备，请等待至完成", MessageBoxImage.Warning);
                return;
            }
            bool isLeft = true;
            int bacteriaCount=publicResourceViewModel.BacteriaNames.Count;
            for (int i = 1; i <= shelfCount; i++)
            {
                for (int j = indexStart; j <= indexEnd; j++)
                {
                    Table_MonitorMes item = serviceDevice.Items64.Where(o => o.Shelf == i && o.Index == j).FirstOrDefault();
                    item.PlateID = _sampleIdCount.ToString("D6");
                    item.PlateType = mICPlateMes.microplateAntibioticConcentrationMes[1].name;
                    item.SampleID = _sampleIdCount.ToString("D6");
                    int index = _random.Next(bacteriaCount);
                    item.SampleType = publicResourceViewModel.BacteriaNames[index];
                    int time = _random.Next(1, 3);
                    item.CultureTime =  1 * 60 * 60;
                    item.State = HoleState.WaitingForSample;
                    item.LoadTime = DateTime.Now;
                    if (isLeft)
                    {
                        item.LorR = 0;
                        isLeft = false;
                    }
                    else
                    {
                        item.LorR = 1;
                        isLeft = true;
                    }
                    monitorMesRepository.AddMonitorMes(item);
                    _sampleIdCount++;
                }
            }
            serviceDevice.IsOpenTest = true;
            DiscontinueEnabled = true;
            _=Refash();
        }

        private async Task Refash()
        {
            await Task.Run(async () =>
            {
                while (true)
                {
                    var doneSamples = serviceDevice.Items64.Where(o => o.State == HoleState.DONE).ToList();
                    if (doneSamples != null && doneSamples.Count > 0)
                    {
                        foreach(var sample in doneSamples)
                        {
                            sample.State = HoleState.WaitingForSample;
                            sample.LoadTime = DateTime.Now;
                            sample.PlateID= _sampleIdCount.ToString("D6");
                            sample.SampleID=_sampleIdCount.ToString("D6");
                            _sampleIdCount++;
                        }
                    }
                    await Task.Delay(1000);
                }
            });
        }

        private void DiscontinueTest()
        {
            DiscontinueEnabled = false;
            StartEnabled = true;
            serviceDevice.DiscontinueDevice();
        }
        #endregion
        #endregion
    }
}
